<template>
  <div id='GoodsAdd'>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品列表</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <!-- 提示区域 -->
      <el-alert title="添加商品信息" type="info" :closable="false" center show-icon>
      </el-alert>
      <!-- 步骤条区域 -->
      <el-steps :active="activeStep - 0" finish-status="success" class="stepClass" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- 竖向标签页 -->
      <el-form :model="addForm" ref="addFormRef" :rules="rulesForm" label-width="100px" class="demo-ruleForm"
        label-position="top">
        <el-tabs v-model="activeStep" tab-position="left" :before-leave="beforeTabLeave" @tab-click="tabClick">
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addForm.goods_name" size="mini"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addForm.goods_price" size="mini" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addForm.goods_weight" size="mini" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addForm.goods_number" size="mini" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <!-- 级联选择器 -->
              <el-cascader v-model="addForm.goods_cat" :options="categoriesList" :props="categoriesProps"
                @change="handleChange">
              </el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <el-form-item v-for="(item) in goodsArgument" :key="item.attr_id" :label="item.attr_name">
              <!-- 复选框数组 -->
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox v-for="(attrValues, index1) in item.attr_vals" :key="index1" :label="attrValues" border
                  size="mini"></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item :label="item.attr_name" v-for="(item) in goodsAttributes" :key="item.attr_id">
              <el-input v-model="item.attr_vals" size="mini"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <!-- 商品图片区域 -->
            <el-upload :action="loadPic" :on-preview="handlePreview" :on-remove="handleRemove" list-type="picture"
              :headers="subPicHeader" :on-success="handleSuccess">
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不超过500kb</div>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <quill-editor v-model="addForm.goods_introduce"></quill-editor>
            <el-button type="primary" style="margin-top:15px" @click="addGoods">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <!-- 图片预览弹出框 -->
    <el-dialog title="图片预览" :visible.sync="picDialogVisible" width="50%" @close="closeDialog">
      <img :src="picUrl" alt="" class="picClass">
    </el-dialog>
  </div>
</template>

<script>
import _ from 'lodash'
export default {
  name: 'GoodsAdd',
  data() {
    return {
      picUrl: '',
      picDialogVisible: false,
      // 上传图片的地址
      loadPic: 'http://127.0.0.1:8888/api/private/v1/upload',
      subPicHeader: {
        Authorization: window.sessionStorage.getItem('token')
      },
      // 商品属性数据
      goodsAttributes: [],
      // 商品参数数据
      goodsArgument: [],
      // 步骤条的进度
      activeStep: '0',
      // 添加商品的表单对象
      addForm: {
        goods_name: '',
        goods_price: 0,
        goods_weight: 0,
        goods_number: 0,
        goods_cat: [],
        pics: [],
        goods_introduce: '',
        attrs: []
      },
      // 商品分类列表
      categoriesList: [],
      // 三级列表选项配置
      categoriesProps: {
        expandTrigger: 'hover',
        children: 'children',
        label: 'cat_name',
        value: 'cat_id',
        attrs: []
      },
      // 添加商品的表单数据验证对象
      rulesForm: {
        goods_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' },
          { min: 1, message: '长度在 1 个字符以上', trigger: 'blur' }
        ],
        goods_price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' }
        ],
        goods_weight: [
          { required: true, message: '请输入商品重量', trigger: 'blur' }
        ],
        goods_number: [
          { required: true, message: '请输入商品数量', trigger: 'blur' }
        ],
        goods_cat: [
          { required: true, message: '请选择商品分类', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    async getCategories() {
      const { data, meta } = await this.$http.get('categories')
      if (meta.status !== 200) return this.$message.error('商品分类数据获取失败')
      this.categoriesList = data
      console.log(this.categoriesList)
    },
    handleChange() {
      if (this.addForm.goods_cat.length !== 3) {
        this.addForm.goods_cat = []
        this.$message.error('商品分类只允许选择第三级分类')
      }
      console.log(this.addForm.goods_cat)
    },
    beforeTabLeave(activeName, oldActiveName) {
      if (oldActiveName === '0' && this.addForm.goods_cat.length !== 3) {
        this.$message.error('请先选择商品分类')
        return false
      }
    },
    async tabClick() {
      if (this.activeStep === '1') {
        const { data, meta } = await this.$http.get(`categories/${this.cateId}/attributes`, { params: { sel: 'many' } })
        if (meta.status !== 200) return this.$message.error(meta.msg)
        data.forEach(item => {
          item.attr_vals = item.attr_vals.length === 0 ? [] : item.attr_vals.split(' ')
        })
        this.goodsArgument = data
        console.log(this.goodsArgument)
      } else if (this.activeStep === '2') {
        const { data, meta } = await this.$http.get(`categories/${this.cateId}/attributes`, { params: { sel: 'only' } })
        if (meta.status !== 200) return this.$message.error(meta.msg)
        this.goodsAttributes = data
        console.log(this.goodsAttributes)
      }
    },
    // 上传图片相关函数
    handleRemove(file) {
      const { tmp_path } = file.response.data
      const index = this.addForm.pics.findIndex(x => x.pic === tmp_path)
      this.addForm.pics.splice(index, 1)
      this.$message.success('图片撤销成功')
    },
    handlePreview(file) {
      console.log('handlePreview')
      const { url } = file.response.data
      console.log(url)
      this.picUrl = url
      this.picDialogVisible = true
    },
    handleSuccess(response) {
      console.log(response)
      const { data } = response
      this.$message.success('图片上传成功')
      const picInfo = { pic: data.tmp_path }
      this.addForm.pics.push(picInfo)
    },
    closeDialog() {
      this.picUrl = ''
    },
    addGoods() {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) {
          return this.$message.error('请填写必要的表单项')
        }
        this.goodsArgument.forEach(item => {
          const goodsArgumentInfo = { attr_id: item.attr_id, attr_value: item.attr_vals.join(' ') }
          this.addForm.attrs.push(goodsArgumentInfo)
        })
        this.goodsAttributes.forEach(item => {
          const goodsAttributesInfo = { attr_id: item.attr_id, attr_value: item.attr_vals }
          this.addForm.attrs.push(goodsAttributesInfo)
        })
        const form = _.cloneDeep(this.addForm)
        form.goods_cat = form.goods_cat.join(',')
        console.log(form)
        const { meta } = await this.$http.post('goods', form)
        if (meta.status !== 201) return this.$message.error(meta.msg)
        this.$message.success('添加商品成功')
        this.$router.push('/goods')
      })
    }
  },
  created() {
    this.getCategories()
  },
  computed: {
    cateId() {
      if (this.addForm.goods_cat.length === 3) {
        return this.addForm.goods_cat[2]
      }
      return null
    }
  }
}
</script>

<style lang="less" scoped>
.stepClass {
  margin-top: 15px;
}

/deep/.el-step__title {
  font-size: 14px;
}

/deep/.el-tabs--left {
  margin-top: 15px;
}

/deep/.el-form-item__label {
  line-height: 20px;
}

/deep/.el-checkbox {
  margin: 0 10px 0 0 !important;
}

.picClass {
  width: 100%;
}

/deep/.ql-editor {
  min-height: 400px;
}
</style>
